package com.yehun.web.controller;


import com.yehun.entity.Test;
import com.yehun.service.TestService;
import com.yehun.utils.ExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
public class HomeController extends BaseController {

    private final static Logger logger = LoggerFactory.getLogger(HomeController.class);

    @Autowired
    private TestService testService;

    @ResponseBody
    @RequestMapping(value = "")
    public String index() {
        //ModelAndView view = new ModelAndView();
        //view.setViewName("/index");
        //view.addObject("message", "my is message");
        //view.setViewName("redirect:dialog");
        //return view;
        return "loading...";
    }

    @RequestMapping(value = "dialog")
    public String dialog() {
        return "dialog";
    }

    @RequestMapping(value = "socket")
    public String socket() {
        return "/socket";
    }

    @RequestMapping(value = "exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        List<Test> tests = testService.list();
        if (tests != null) {
            String title = "Test";
            String[] headers = new String[] { "ID", "Name", "Value", "Date" };
            ExcelUtils excelUtils = new ExcelUtils(title, headers, response.getOutputStream());
            //ExcelUtils excelUtils = new ExcelUtils(title, headers, "/home/yehun/111.xlsx");
            try {
                int i = 0;
                Object[] bodys;
                for (Test test : tests) {
                    bodys = new Object[4];
                    bodys[0] = test.getId();
                    bodys[1] = test.getName();
                    bodys[2] = test.getValue();
                    bodys[3] = test.getDate();
                    excelUtils.addRow(i, bodys);
                    i++;
                }
                excelUtils.setResponse(response, "222.xlsx");
                excelUtils.write();
            } finally {
                excelUtils.dispose();
            }
        }
    }

}
